package com.hxh.order.message;

import com.fasterxml.jackson.core.type.TypeReference;
import com.hxh.order.utils.JsonUtil;
import com.hxh.product.common.ProductInfoOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author huangxunhui
 * Date: Created in 18/9/28 下午4:28
 * Utils: Intellij Idea
 * Description: 订单信息接收
 */
@Slf4j
@Component
public class ProductInfoRecevier {


    private static final String  PRODUCT_STOCK_TEMPLATE = "product_stock_%s";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(queuesToDeclare = @Queue("productInfo"))
    public void process(String message){
        //message => ProductInfoOutput
        List<ProductInfoOutput> productInfoOutputList = (List<ProductInfoOutput>) JsonUtil.formJson(message,
                new TypeReference<List<ProductInfoOutput>>() {} );
        log.info("从队列【{}】接收到的消息:{}","productInfo",productInfoOutputList);

        //存到redis里面去
        productInfoOutputList.forEach(productInfoOutput -> {
            stringRedisTemplate.opsForValue().set(String.format(PRODUCT_STOCK_TEMPLATE , productInfoOutput.getProductId()) ,
                    productInfoOutput.getProductStock().toString());
        });
    }
}
